package ha.web.client.servlet.adminPage;

import ha.web.server.database.UserId;
import ha.web.server.exceptions.UserNotFoundException;
import ha.web.server.manager.GameMangerServerSide;
import ha.web.server.manager.GameRunning;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class adminPage
 */
@WebServlet("/AdminPage")
public class AdminPage extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AdminPage() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @throws IOException 
	 * @throws ServletException 
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void forward2login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		ServletContext context = getServletContext();
		RequestDispatcher dispatcher = context.getRequestDispatcher("/Login");
		dispatcher.forward(request, response);	
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		GameMangerServerSide ins = GameMangerServerSide.getInstance();
		int userId = -1;
		int gameId;
		String me;
		boolean cookieFound = false;
		Cookie[] userCookie = request.getCookies();
		for(int i=0; i<userCookie.length; i++) {
			if ("chinese_checkers".equals(userCookie[i].getName())) {
				String tmp = userCookie[i].getValue();
				String[] cookie = tmp.split(":");
				userId = Integer.parseInt(cookie[1]);
				cookieFound = true;
			}
		}
		if(!cookieFound) {

			return;
		}
		try {	

			if (! ins.isUserAdmin(userId)){
				forward2login(request, response);
			}
			else{
				me = ins.getPlayerById(userId).getName();
				showAdminPage(request, response,me);
			}
		} catch (UserNotFoundException e) {	
			forward2login(request, response);
			return;
		}

	}
	private void showAdminPage(HttpServletRequest request, HttpServletResponse response, String me) throws IOException{
		PrintWriter out = response.getWriter();
		out.print("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">");
		out.print("<HTML><HEAD><TITLE>The ultimate battle of Chinese Checkers</TITLE>");
		out.print("<META http-equiv=Content-Type content=\"text/html\">");
		out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"gameDesign.css\" />");
		out.print("</HEAD><BODY><P>");
		try
		{
			out.print("<div align=\"center\">");
			out.print("<h1>2P chinese checkers</h1>");	
			out.print("<h2>Welcome Administrator " + me + "</h2>");	
			//get all games and show them here
			GameMangerServerSide ins = GameMangerServerSide .getInstance();
			//getWaitingList
			out.print("<form><input type=button class=\"button\" value=\"Refresh\" onClick=\"window.location.reload()\"></form>");
			out.print("<h2>Waiting list:</h2>");	
			
			List<UserId> wl = ins.getWaitingList();		
			if (wl.size()== 0){
				out.print("<h3>NO one in waiting list</h3><br><hr>");
			}else{
				for(int i=0;i<wl.size();i++){
					out.print("<h3>" + wl.get(i).getName() +"</h3><br><hr>");
				}
			}
			out.print("<h2>Current games:</h2>");	
			Set<Integer> gamesIds = ins.getGamesId();
			Iterator<Integer> it = gamesIds.iterator();
			while (it.hasNext()){
				Integer gameNum = it.next();
				GameRunning cGame= ins.getGameById(gameNum);
				if (cGame.gameEnded()== false){
					List<Integer> players =cGame.getPlayers();
					String p1 = cGame.getPlayerNameById(players.get(0));
					String p2 = cGame.getPlayerNameById(players.get(1));
			        out.print("<h3>game " + gameNum.toString() +" : player 1 is " + p1 + " and player 2 is " + p2 + "</h3><br><hr>");
				}
				
			}
			out.print("</BODY></HTML>");
		}
	finally{

		out.print("<meta http-equiv=\"refresh\" content=\"N; URL=login\">");
		out.print("</BODY></HTML>");

	}
	}
	

}
